package com.pt25.base.dep.redis.aspect;


import com.pt25.base.dep.redis.RedisService;
import com.pt25.base.util.JsonUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RBatch;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.Duration;

@Slf4j
@Aspect
@Component
public class SaveCacheAspect extends BaseCacheAspect {
    @Resource
    private RedisService redisService;

    @Around("@annotation(com.pt25.base.dep.redis.aspect.SaveCache)")
    public Object saveCache(ProceedingJoinPoint pjp) throws Throwable {
        Method method = getMethod(pjp);
        //1、获取注解
        SaveCache saveCache = method.getAnnotation(SaveCache.class);
        //2、获取缓存key
        String dataCacheKey = getDataCacheKey(pjp, method, saveCache.cacheKey(), saveCache.value().getName());
        //3、缓存数据
        Object returnValue = pjp.proceed();
        if (null != dataCacheKey && (saveCache.cacheNull() || null != returnValue)) {
            log.info("dataCacheKey:{}", dataCacheKey);
            RedissonClient redissonClient = redisService.getRedissonClient(saveCache.redisName());
            RBatch batch = redissonClient.createBatch();
            batch.getBucket(dataCacheKey, new StringCodec()).setAsync(returnValue == null ? "{}" : JsonUtil.toJson(returnValue));
            batch.getBucket(dataCacheKey, new StringCodec()).expireAsync(Duration.ofMinutes(saveCache.expiredTime()));
            batch.execute();
        }
        return returnValue;
    }
}

